_G = GLOBAL
TheNet = _G.TheNet
TheSim = _G.TheSim

tick = GetModConfigData("tick")
disable_willow = GetModConfigData("disable_willow")
disable_numberid = GetModConfigData("disable_numberid")

local weblist = {}
local banlist = {}

local function ban()
    for _,v in pairs(_G.AllPlayers) do
        if table.contains(weblist, v.userid) then
            v:PushEvent('death')
            TheNet:Ban(v.userid)
            table.insert(banlist, v.userid)
        end
    end

    for _,v in ipairs(weblist) do
        if not table.contains(banlist, v) then
            print(v)
            TheNet:Ban(v)
            table.insert(banlist, v)
        end
    end
end

function split_string(text)
    local res = {}
    local t = text:split("\n")
    for _,v in ipairs(t) do
        v:gsub("\n", "")
        table.insert(res, v)
    end
    return res
end

local function mainfn(inst)
    if TheSim == nil or TheNet == nil then 
        return
    end

    ban()

    TheSim:QueryServer("https://gitee.com/ilv/Blocklist/raw/master/blocklist.txt", function(result, isSuccessful, resultCode)
        if not isSuccessful or resultCode ~= 200 or string.len(result) == 0 then
            return
        end

        weblist = split_string(result)
        ban()
    end)
end

AddPrefabPostInit("world", function(inst)
    inst:DoPeriodicTask(tick, mainfn, 0)
end)

AddPlayerPostInit(function(player)
    if (disable_willow == 1 and player.prefab == "willow") or
       (disable_numberid == 1 and player.name:match("%d+") ~= ni and #player.name:match("%d+") == #player.name) then
        TheNet:Ban(player.userid)
        table.insert(banlist, player.userid)
        return
    end
end)